package com.tl.sun.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.allenliu.badgeview.BadgeFactory;
import com.allenliu.badgeview.BadgeView;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.orhanobut.logger.Logger;
import com.tl.sun.AppConfig;
import com.tl.sun.AppContext;
import com.tl.sun.OkHeader;
import com.tl.sun.R;
import com.tl.sun.event.MainEvent;
import com.tl.sun.event.MesEvent;
import com.tl.sun.helper.UIHelper;
import com.tl.sun.manager.MDAccountMgr;
import com.tl.sun.manager.MDUserMgr;
import com.tl.sun.model.BaseModel;
import com.tl.sun.model.UseInfo;
import com.tl.sun.model.UserEnetity;
import com.tl.sun.ui.activity.AccountInfoActivity;
import com.tl.sun.ui.activity.ReplacePhoneActivity;
import com.tl.sun.ui.activity.SoftwareSettingActivity;
import com.tl.sun.ui.activity.SystemMsgActivity;
import com.tl.sun.ui.activity.TerminalActivity;
import com.tl.sun.ui.activity.WebViewActivity;
import com.tl.sun.utils.DataCleanManager;
import com.tl.sun.utils.MDUtil;
import com.tl.sun.utils.ToastUtil;
import com.tl.sun.utils.core.EmptyUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;


public class MeFragment extends Fragment {

    @Bind(R.id.tv_me_bind_phone)
    TextView mTvMeBindPhone;
    @Bind(R.id.tv_me_name)
    TextView mTvMeName;
    @Bind(R.id.tv_day)
    TextView mTvDay;
    @Bind(R.id.rl_go_bind_phone)
    RelativeLayout mRlGoBindPhone;
    @Bind(R.id.tv_cache)
    TextView mTvCache;
    @Bind(R.id.tv_use_sale)
    TextView mTvSale;
    @Bind(R.id.iv_vip_logo)
    ImageView mIvVipLogo;
    @Bind(R.id.iv_del)
    ImageView mIvDel;
    @Bind(R.id.rl_push_msg)
    RelativeLayout mRlPushMsg;
    @Bind(R.id.iv_msg)
    ImageView mIvBedge;


    private View rootView;

    private UserEnetity userInfo;
    private BadgeView mBadgeView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.activity_me, container, false);
            ButterKnife.bind(this, rootView);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
    }

    @Override
    public void onStart() {
        super.onStart();
        getUserInfo();
        getMeal();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(getActivity());
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }


    @OnClick({R.id.tv_me_bind_phone, R.id.iv_del, R.id.rl_push_msg, R.id.ll_go_buy,
            R.id.tv_account_info, R.id.tv_terminal_online, R.id.tv_buy_record, R.id.tv_use_record,
            R.id.tv_setting, R.id.ll_clean_cache, R.id.tv_about_we, R.id.ll_me_out,
            R.id.tv_use_sale})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_me_bind_phone:
                Intent phone = new Intent(getActivity(), ReplacePhoneActivity.class);
                Bundle phoneb = new Bundle();
                phoneb.putString("phone", userInfo.getPhone());
                phoneb.putString("name", userInfo.getUsername());
                phone.putExtras(phoneb);
                startActivity(phone);
                break;
            case R.id.iv_del:
                mTvMeBindPhone.setVisibility(View.GONE);
                mIvDel.setVisibility(View.GONE);
                break;
            case R.id.ll_go_buy:
                EventBus.getDefault().post(new MainEvent(1));
                break;
            case R.id.rl_push_msg:
                Intent intent = SystemMsgActivity.newIntent();
                startActivity(intent);
                break;
            case R.id.tv_account_info:
                Intent account = new Intent(getActivity(), AccountInfoActivity.class);
                startActivity(account);
                break;
            case R.id.tv_terminal_online:
                Intent termianl = new Intent(getActivity(), TerminalActivity.class);
                startActivity(termianl);
                break;
            case R.id.tv_buy_record:
                mWebViewIntent("购买记录", AppConfig.getInstance().getAppInfo().getRecords());
                break;
            case R.id.tv_use_record:
                mWebViewIntent("使用记录", AppConfig.getInstance().getAppInfo().getUserRecord());
                break;
            case R.id.tv_use_sale:
                String userId = MDUtil.mdEncrypts(String.valueOf(MDUserMgr.getInstance().getId()));
                UIHelper.goWebViewIntent(getActivity(), "售后服务", AppConfig.getInstance().getAppInfo().getServiceUrl() + "&id=" + userId);
                break;
            case R.id.tv_setting:
                Intent set = new Intent(getActivity(), SoftwareSettingActivity.class);
                startActivity(set);
                break;
            case R.id.ll_clean_cache:
                DataCleanManager.clearAllCache(getActivity());
                getCache();
                break;
            case R.id.tv_about_we:
                mWebViewIntent("关于我们", AppConfig.getInstance().getAppInfo().getAboutUrl());
                break;
            case R.id.ll_me_out:
                loginOut();
                break;
            default:
                break;
        }
    }


    /**
     * 获取用户信息
     */
    public void getUserInfo() {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "account/get_user_all")
                .tag(getActivity())
                .upJson(mapSession())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Logger.e("用户信息:" + s);
                        Gson gson = new Gson();
                        Type userType = new TypeToken<BaseModel<UserEnetity>>() {
                        }.getType();
                        BaseModel<UserEnetity> baseModel;
                        try {
                            baseModel = gson.fromJson(s, userType);
                        } catch (JsonSyntaxException e) {
                            baseModel = gson.fromJson(s, BaseModel.class);
                        }
                        if (baseModel.getRet().equals("0")) {
                            userInfo = baseModel.getData();
                            if (EmptyUtils.isEmpty(baseModel.getData().getPhone())) {
                                mRlGoBindPhone.setVisibility(View.VISIBLE);
                            } else {
                                mRlGoBindPhone.setVisibility(View.GONE);
                            }
                            String username = baseModel.getData().getShowNmae();
                            if (!TextUtils.isEmpty(username)) {
                                mTvMeName.setText(username);
                            }

                            String msgCount = baseModel.getData().getMsgCount();//消息数量

                            if (!msgCount.equals("0")) {
                                if (mBadgeView == null) {
                                    mBadgeView = BadgeFactory.create(getActivity());
                                }
                                mBadgeView
                                        .setTextColor(Color.WHITE)
                                        .setWidthAndHeight(15, 15)
                                        .setBadgeBackground(Color.RED)
                                        .setTextSize(10)
                                        .setBadgeGravity(Gravity.RIGHT | Gravity.TOP)
                                        .setBadgeCount(msgCount)
                                        .setSpace(4, 4)
                                        .setShape(BadgeView.SHAPE_CIRCLE)
                                        .bind(mIvBedge);
                            } else {
                                if (mBadgeView != null)
                                    mBadgeView.unbind();
                            }

                            getCache();
                        } else {
                            ToastUtil.showToast(baseModel.getMsg());
                        }
                    }
                });
    }

    /**
     * 退出登录
     */
    public void loginOut() {
        HashMap<String, String> map = new HashMap<>();
        map.put("token", MDUtil.mdEncrypt(MDAccountMgr.getInstance().getSessionId()));
        JSONObject jsonObject = new JSONObject(map);
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity())).post(AppContext.getInstance().getBaseUrl() + "account/quit")
                .tag(getActivity())
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        BaseModel baseModel = gson.fromJson(s, BaseModel.class);
                        if (baseModel.getRet().equals("0")) {
                            UIHelper.goLoginPage(getActivity());
                        } else {
                            UIHelper.goLoginPage(getActivity());
                        }
                    }
                });
    }

    /**
     * 获取用户套餐信息
     */
    private void getMeal() {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity())).post(AppContext.getInstance().getBaseUrl() + "ucenter/check_user_info")
                .tag(this)
                .upJson(mapSession())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject jo = new JSONObject(s);
                            String ret = jo.getString("ret");
                            String code = jo.getString("code");
                            String msg = jo.getString("msg");
                            if (ret.equals("0") && code.equals("1")) {
                                UseInfo useInfo = new Gson().fromJson(s, UseInfo.class);
                                mTvDay.setText(useInfo.getRet_data().getLast_time() + useInfo.getRet_data().getLast_time_type());
                                if (useInfo.getRet_data().getVipType().equals("1")) {
                                    mIvVipLogo.setVisibility(View.VISIBLE);
                                    mIvVipLogo.setSelected(true);
                                } else if (useInfo.getRet_data().getVipType().equals("2")) {
                                    mIvVipLogo.setVisibility(View.VISIBLE);
                                    mIvVipLogo.setSelected(false);
                                } else {
                                    mIvVipLogo.setVisibility(View.GONE);
                                }
                            } else if (ret.equals("1") && code.equals("-1")) {

                            }
                        } catch (Exception e) {
                        }

                    }
                });
    }

    /**
     * 跳转到 webview
     *
     * @param title
     * @param url
     */
    public void mWebViewIntent(String title, String url) {
        Intent webview = new Intent(getActivity(), WebViewActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("title", title);
        bundle.putString("url", url);
        webview.putExtras(bundle);
        startActivity(webview);
    }

    /**
     * 获取缓存
     */
    public void getCache() {
        try {
            mTvCache.setText(DataCleanManager.getTotalCacheSize(getActivity()));
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    /**
     * 网络请求参数
     *
     * @return
     */
    private String mapSession() {
        HashMap<String, String> map = new HashMap<>();
        map.put("session_id", MDAccountMgr.getInstance().getSessionId());
        JSONObject json = new JSONObject(map);
        return json.toString();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(MesEvent event) {
        if (event.getMepay() == 1) {
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    //execute the task
                    EventBus.getDefault().post(new MainEvent(1));
                }
            }, 1000);
        }
    }
}
